from flask import Blueprint, views, render_template, request, session, redirect, url_for, g, jsonify
from .forms import (
    LoginForm,
    ResetPwdForm,
    ResetEmailForm,
    BannerForm,
    UpdateBannerForm,
    AddBoardForm,
    UpdateBoardForm
)
from .models import CMSUser, CMSPermission
from apps.models import BannerModels, BoardModels, PostModels, HighlightPostModels
import config
from exts import db, mail
from apps.cms.describes import login_request, permission_request
from utils import resful, zlcache
from flask_mail import Message
import string, random
from tasks import send_message


bp = Blueprint("cms", __name__)


@bp.route("/")
@login_request
def index():
    # print(g.cms_user)
    return render_template("cms/cms_index.html")


@bp.route("/logout/")
def logout():
    session.pop(config.CMS_USER_ID)
    return redirect(url_for("cms.login"))


@bp.route("/profile/")
@login_request
def profile():
    return render_template("cms/cms_profile.html")


@bp.route("/boards/")
@login_request
@permission_request(CMSPermission.BOAEDER)
def boards():
    boards_models = BoardModels.query.all()
    context = {
        "boards": boards_models
    }
    return render_template("cms/cms_boards.html", **context)


@bp.route("/aboards/", methods=["POST"])
@login_request
@permission_request(CMSPermission.BOAEDER)
def aboards():
    form = AddBoardForm(request.form)
    if form:
        name = form.name.data
        board = BoardModels(name=name)
        db.session.add(board)
        db.session.commit()
        return resful.success()
    else:
        return resful.paraserror(message=form.get_errors())


@bp.route("/uboards/", methods=["POST"])
@login_request
@permission_request(CMSPermission.BOAEDER)
def uboard():
    form = UpdateBoardForm(request.form)
    if form.validate():
        board_id = form.board_id.data
        name = form.name.data
        board = BoardModels.query.get(board_id)
        if board:
            board.name = name
            db.session.commit()
            return resful.success()
        else:
            return resful.paraserror(message="没有这个模块")
    else:
        return resful.paraserror(message=form.get_errors())


@bp.route("/dboards/", methods=["POST"])
@login_request
@permission_request(CMSPermission.BOAEDER)
def dboards():
    board_id = request.form.get("board_id")
    print(board_id)
    if not board_id:
        return resful.paraserror(message="请输入模块id")

    board = BoardModels.query.get(board_id)
    if not board:
        return resful.paraserror(message="没有这个模块")

    db.session.delete(board)
    db.session.commit()
    return resful.success()


@bp.route("/cuser/")
@login_request
@permission_request(CMSPermission.CMSUSER)
def cuser():
    return render_template("cms/cms_cusers.html")


@bp.route("/roles/")
@login_request
@permission_request(CMSPermission.FRONTUSER)
def roles():
    return render_template("cms/cms_roles.html")


@bp.route("/fusers/")
@login_request
@permission_request(CMSPermission.FRONTUSER)
def fusers():
    return render_template("cms/cms_fusers.html")


@bp.route("/comments/")
@login_request
@permission_request(CMSPermission.COMMENTER)
def comments():
    return render_template("cms/cms_comments.html")


@bp.route("/posts/")
@login_request
@permission_request(CMSPermission.POSTER)
def posts():
    all_posts = PostModels.query.all()
    context = {
        "posts": all_posts
    }
    return render_template("cms/cms_posts.html", **context)


@bp.route("/alight/", methods=["POST"])
@login_request
def ahighlight():
    # 当get请求时，需要使用request.args来获取数据
    # 当post请求时，需要使用request.form来获取数据
    post_id = request.form.get("post_id")
    if not post_id:
        return resful.paraserror(message="请传入帖子")
    post = PostModels.query.get(post_id)
    if not post:
        return resful.paraserror("沒有这篇帖子")
    highlight = HighlightPostModels(post_id=post_id)
    db.session.add(highlight)
    db.session.commit()
    return resful.success()

@bp.route("/ulight/", methods=["POST"])
@login_request
def uhighlight():
    post_id = request.form.get("post_id")
    if not post_id:
        return resful.paraserror(message="请传入帖子")

    post = PostModels.query.get(post_id)
    if not post:
        return resful.paraserror(message="沒有这篇帖子")
    highlight = HighlightPostModels.query.filter(HighlightPostModels.post_id == post_id).first()
    db.session.delete(highlight)
    db.session.commit()
    return resful.success()

@bp.route("/cmsuser_manage/")
@login_request
@permission_request(CMSPermission.CMSUSER)
def cmsuser_manage():
    return render_template("cms/cmsuser_manage.html")


@bp.route("/cmsrole_manage/")
@login_request
@permission_request(CMSPermission.ALL_PERMISSION)
def cmsrole_manage():
    return render_template("cms/cmsrole_manage.html")


@bp.route("/banner/")
@login_request
def banner():
    banners = BannerModels.query.all()
    return render_template("cms/cms_banner.html", banners=banners)


@bp.route("/abanner/", methods=["POST"])
@login_request
def abanner():
    form = BannerForm(request.form)
    if form.validate():
        name = form.name.data
        image_url = form.image_url.data
        link_url = form.link_url.data
        priority = form.priority.data
        banners = BannerModels(name=name, image_url=image_url, link_url=link_url, priority=priority)
        db.session.add(banners)
        db.session.commit()
        return resful.success()
    else:
        return resful.paraserror(message=form.get_errors())


@bp.route("/ubanner/", methods=["POST"])
@login_request
def ubanner():
    form = UpdateBannerForm(request.form)
    if form.validate():
        name = form.name.data
        image_url = form.image_url.data
        link_url = form.link_url.data
        priority = form.priority.data
        banner_id = form.banner_id.data

        banner = BannerModels.query.get(banner_id)

        if banner:
            banner.name = name
            banner.image_url = image_url
            banner.link_url = link_url
            banner.priority = priority
            db.session.commit()

            return resful.success()
        else:
            return resful.paraserror(message="没有这个轮播图")
    else:
        return resful.paraserror(message=form.get_errors())


@bp.route("/dbanner/", methods=["POST"])
def dbanner():
    banner_id = request.form.get("banner_id")
    if not banner_id:
        return resful.paraserror(message="请传入轮播图ID!")

    banner = BannerModels.query.get(banner_id)
    if not banner:
        return resful.paraserror(message="没有这个轮播图!")

    db.session.delete(banner)
    db.session.commit()

    return resful.success()


class ResetPwd(views.MethodView):
    decorators = [login_request]

    def get(self):
        return render_template("cms/cms_resetpwd.html")

    def post(self):

        form = ResetPwdForm(request.form)

        if form.validate():
            oldpwd = form.oldpwd.data
            newpwd = form.newpwd.data
            user = g.cms_user

            # print(oldpwd, newpwd)
            if user.check_password(oldpwd):
                user.password = newpwd
                db.session.commit()
                # 返回给前段的格式：{"code":200,"message":""}
                return resful.success()
            else:
                return resful.paraserror(message="旧密码验证错误")
        else:
            message = form.get_errors()
            return resful.paraserror(message=message)


class ResetEmail(views.MethodView):
    decorators = [login_request]

    def get(self):
        return render_template("cms/cms_resetemail.html")

    def post(self):

        form = ResetEmailForm(request.form)
        if form.validate():
            email = form.email.data
            user = g.cms_user
            # print(user.email)
            user.email = email
            db.session.commit()
            return resful.success()
        else:
            return resful.paraserror(message=form.get_errors())


@bp.route("/email_captcha/")
def email_captcha():
    # /send_captcha/?email=xxxx@qq.com

    email = request.args.get("email")
    if not email:
        return resful.paraserror(message="请传递邮箱参数")
    captcha_str = list(string.ascii_letters)
    captcha_code = captcha_str + ["1", "2", "3", "4", "5", "6", "7", "8", "9"]
    captcha = "".join(random.sample(captcha_code, 6))

    # 把验证码发送给客户
    # message = Message("PYTHON论坛验证码", recipients=[email], body="验证码为: %s" % captcha)
    # # print(message)
    # try:
    #     mail.send(message)
    send_message.delay("PYTHON论坛验证码", recipients=[email], body="验证码为: %s" % captcha)
    # except:
    #     return resful.servererror()
    zlcache.set(email, captcha)

    return resful.success()


class LoginView(views.MethodView):
    def get(self, message=None):
        return render_template("cms/cms_login.html", message=message)

    def post(self):
        form = LoginForm(request.form)
        if form.validate():
            email = form.email.data
            password = form.password.data
            remember = form.remember.data
            user = CMSUser.query.filter(CMSUser.email == email).first()

            # models定义了密码验证方式
            if user and user.check_password(password):
                session[config.CMS_USER_ID] = user.id
                if remember:
                    # 勾选记住我，session 保持31天
                    session.permanent = True
                return redirect(url_for("cms.index"))

            else:

                # ('password': ['密码的长度是2位到20位'])
                return self.get(message="邮箱或者密码错误")
        else:
            # print(form.errors)
            messsage = form.get_errors()
            return self.get(message=messsage)


bp.add_url_rule("login", view_func=LoginView.as_view("login"))
bp.add_url_rule(("resetpwd"), view_func=ResetPwd.as_view("resetpwd"))
bp.add_url_rule(("resetemail"), view_func=ResetEmail.as_view("resetemail"))
